import MySQLdb

def db_connect():
    try:
        conn = MySQLdb.connect (host = "64.186.135.177",
                               user = "root",
                               passwd = "lordillusions",
                               db = "stocks_db",
                               port = 4465)
        
        """
        conn = MySQLdb.connect (host = "127.0.0.1",
                               user = "root",
                               passwd = "lordillusions",
                               db = "stocks_db_archive",
                               port = 3306)
        
        conn = MySQLdb.connect (host = "127.0.0.1",
                               user = "root",
                               passwd = "lordillusions",
                               db = "stocks_db",
                               port = 4465)
        """
        cursor = conn.cursor()
        
    except MySQLdb.Error, e:
        print "Error Connect %d: %s" % (e.args[0], e.args[1])
        #sys.exit (1)
    
    return cursor,conn

def db_executeQuery(query):
    
    try:
        cursor,conn = db_connect()
        if query.strip().startswith(upper("SELECT")):
            response = cursor.execute (query)
            return response
        else:
            cursor.execute (query)
        
        
        
    except MySQLdb.Error, e:
        print "Error Execute %d: %s" % (e.args[0], e.args[1])
        
    finally:
        db_disconnect(cursor,conn)
        #sys.exit (1)
    
        
def db_disconnect(cursor,conn):
    try:
        cursor.close ()
        conn.commit ()
        conn.close ()
        
    except MySQLdb.Error, e:
        print "Error Disconnect %d: %s" % (e.args[0], e.args[1])
        sys.exit (1)